/**
 * Copyright 1998-2007, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
package ca.uvic.cs.cogz.mapping.ui.tree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ca.uvic.cs.cogz.mapping.filter.TreeFilterManager;
import ca.uvic.cs.cogz.mapping.ontology.DataLoaderFacade;
import ca.uvic.cs.cogz.util.FrameUtil;
import edu.stanford.smi.protege.model.Cls;
import edu.stanford.smi.protege.model.DefaultCls;
import edu.stanford.smi.protege.model.FrameID;
import edu.stanford.smi.protege.model.KnowledgeBase;
import edu.stanford.smi.protege.model.Slot;
import edu.stanford.smi.protege.ui.ParentChildRoot;
import edu.stanford.smi.protege.ui.SlotSubslotRoot;
import edu.stanford.smi.protege.util.LazyTreeNode;

/**
 * @author Chris Callendar, Sean Falconer
 */
public class FilteredParentChildRoot extends ParentChildRoot implements IFilteredTreeNode {
	public FilteredParentChildRoot(Cls root) {
		super(root);
	}

	@SuppressWarnings("unchecked")
	public FilteredParentChildRoot(Collection roots) {
		super(roots);
	}

	@Override
	public LazyTreeNode createNode(Object o) {
		if(o instanceof DefaultCls) {
			Cls temp = (DefaultCls)o;
			if(temp.getFrameID().getName().equals(Integer.MAX_VALUE + "")) {
				return new SlotSubslotRoot(temp.getKnowledgeBase(), getSlots(temp.getKnowledgeBase()));
			}
		}
		return new FilteredParentChildNode(this, FrameUtil.getCls(o));
	}
	
	public Collection<Slot> getSlots(KnowledgeBase kb) {
		List<Slot> slots = new ArrayList<Slot>();
		
		for(Object o : kb.getSlots()) {
			Slot slot = (Slot)o;
			if(!slot.isSystem()) {
				slots.add(slot);
			}
		}
		
		return slots;
	}
	
	@Override
	protected int getChildObjectCount() {
		return (isFiltered() ? getFilterChildrenCount() : getAllChildrenCount());
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection getChildObjects() {
		if (isFiltered()) {
			return FrameUtil.getSearchMatchedFrames(super.getChildObjects());
		}
		//return super.getChildObjects();
		
		Collection children = new ArrayList();
		
		Cls root = (Cls) ((List) this.getUserObject()).get(0);
		
		if(DataLoaderFacade.getInstance().isShowSlots()) {
			DefaultCls temp = new DefaultCls(root.getKnowledgeBase(), new FrameID(Integer.MAX_VALUE + ""));
		
			children.add(temp);
		}
		children.addAll(super.getChildObjects());

		return children;
	}
	
	public String getToolTipText() {
		return ((Cls) this.getUserObject()).getBrowserText();
	}

	@Override
	public String toString() {
		return "FilteredParentChildRoot(" + getUserObject() + ")";
	}

	// IFilteredTreeNode methods	
	public boolean isFiltered() {
		return TreeFilterManager.getInstance().isTreeFilteringActive();
	}

	public int getFilterChildrenCount() {
		return FrameUtil.getSearchMatchedFrames(super.getChildObjects()).size();
	}

	public int getAllChildrenCount() {
		return super.getChildObjectCount();
	}
}
